package com.atguiguNIO.channel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServerSocketChannelDemo01 {


    public static void main(String[] args) {




        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

            serverSocketChannel.socket().bind(new InetSocketAddress(8080));

            ByteBuffer byteBuffer = ByteBuffer.wrap("hello world".getBytes());


            serverSocketChannel.configureBlocking(false);

            while(true){
                SocketChannel socketChannel = serverSocketChannel.accept();  //监听是否有新连接

                //do something with socketChannel...

                if (socketChannel==null) {

                    System.out.println("等待新连接.........");
                    Thread.sleep(2000);
                }else{
                    System.out.println("链接来自于" +  socketChannel.socket().getRemoteSocketAddress());
                    System.out.println("处理业务中..............");
                    byteBuffer.rewind();
                    socketChannel.write(byteBuffer) ;
                    socketChannel.close();
                    System.out.println("业务处理完毕, 关闭信道.........");

                }



            }

        }catch (Exception e) {
            e.printStackTrace();
        }

    }


}
